// dh-leave_requests 云对象 - 请假申请管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserById, getUserList, getDecryptSecret, decryptRealnameAuth } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-leave_requests] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 获取角色的中文名称
 */
function getRoleText(role) {
	const roleMap = {
		'admin': '超级管理员',
		'manager': '管理员',
		'director': '院长',
		'doctor': '医生',
		'nurse': '护士',
		'administrative': '行政',
		'finance': '财务',
		'purchaser': '采购员'
	};
	return roleMap[role] || role || '员工';
}

/**
 * 为单个请假申请附加员工信息
 */
async function enrichLeaveRequestInfo(request) {
	if (!request) return request;

	// 获取申请人信息（使用统一的用户查询工具）
	if (request.requester_id) {
		try {
			const userInfo = await getUserById(request.requester_id, 'full', false, true);
			
			if (userInfo) {
				request.requester_name = userInfo.realName || userInfo.displayName || '未知';
				
				// 保存完整的角色数组
				let roles = userInfo.role || [];
				if (!Array.isArray(roles)) {
					roles = [roles];
				}
				request.requester_roles = roles;  // 保存完整角色数组
				
				// 同时保存主要角色（兼容旧逻辑）
				const mainRole = roles.find(r => r !== 'user') || roles[0] || 'user';
				request.requester_role = mainRole;
				request.requester_role_text = getRoleText(mainRole);
			}
		} catch (error) {
			console.error('[dh-leave_requests] 获取申请人信息失败:', error);
			request.requester_name = '未知';
			request.requester_role_text = '员工';
		}
	}

	// 获取审批人信息（使用统一的用户查询工具）
	if (request.approved_by) {
		try {
			const approverInfo = await getUserById(request.approved_by, 'default', false, true);
			
			if (approverInfo) {
				request.approver_name = approverInfo.realName || approverInfo.displayName || '未知';
			}
		} catch (error) {
			console.error('[dh-leave_requests] 获取审批人信息失败:', error);
			request.approver_name = '未知';
		}
	}

	return request;
}

/**
 * 为请假申请列表批量附加员工信息
 */
async function enrichLeaveRequestsList(requests) {
	if (!Array.isArray(requests) || requests.length === 0) {
		return requests;
	}

	// 收集所有申请人ID和审批人ID
	const requesterIds = [...new Set(requests.map(r => r.requester_id).filter(Boolean))];
	const approverIds = [...new Set(requests.map(r => r.approved_by).filter(Boolean))];
	const allUserIds = [...new Set([...requesterIds, ...approverIds])];

	if (allUserIds.length === 0) return requests;

	try {
		// 直接查询数据库获取用户信息（不进行角色过滤，确保能获取到所有审批人，包括admin和manager）
		const userRes = await db.collection('uni-id-users')
			.where({
				_id: _.in(allUserIds)
			})
			.field({
				_id: true,
				username: true,
				nickname: true,
				realname_auth: true,
				role: true
			})
			.get();
		
		// 获取解密密钥
		const decryptSecret = await getDecryptSecret();
		
		// 构建用户映射
		const userMap = {};
		if (userRes.data && userRes.data.length > 0) {
			userRes.data.forEach(user => {
				// 解密实名认证信息
				let realName = '';
				if (user.realname_auth && decryptSecret) {
					try {
						const decryptedAuth = decryptRealnameAuth(user.realname_auth, decryptSecret);
						realName = decryptedAuth.real_name || '';
					} catch (err) {
						console.error('[enrichLeaveRequestsList] 解密失败:', err);
					}
				}
				
				// 提取显示名称（优先级：解密后的真实姓名 > nickname > username）
				const displayName = realName || user.nickname || user.username || '未知';
				
				let roles = user.role || [];
				if (!Array.isArray(roles)) {
					roles = [roles];
				}
				const mainRole = roles.find(r => r !== 'user') || roles[0] || 'user';
				
				userMap[user._id] = {
					name: displayName,
					role: mainRole,
					role_text: getRoleText(mainRole)
				};
			});
		}

		// 附加信息到请假申请
		requests.forEach(request => {
			// 申请人信息
			if (request.requester_id && userMap[request.requester_id]) {
				request.requester_name = userMap[request.requester_id].name;
				request.requester_role = userMap[request.requester_id].role;
				request.requester_role_text = userMap[request.requester_id].role_text;
			} else if (request.requester_id) {
				request.requester_name = '未知';
				request.requester_role_text = '员工';
			}

			// 审批人信息
			if (request.approved_by && userMap[request.approved_by]) {
				request.approver_name = userMap[request.approved_by].name;
			} else if (request.approved_by) {
				// approved_by 存在但不在 userMap 中，说明查询失败或用户不存在
				request.approver_name = '未知';
			}
			// 如果 approved_by 不存在（待审批状态），则不设置 approver_name
		});
	} catch (error) {
		console.error('[dh-leave_requests] 批量获取员工信息失败:', error);
		// 即使查询失败，也要为有 approved_by 的记录设置默认值
		requests.forEach(request => {
			if (request.requester_id && !request.requester_name) {
				request.requester_name = '未知';
				request.requester_role_text = '员工';
			}
			if (request.approved_by && !request.approver_name) {
				request.approver_name = '未知';
			}
		});
	}

	return requests;
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-leave_requests] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch', 'approve', 'reject'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 根据ID查询请假申请（自动附加员工信息）
	 */
	async getLeaveRequestById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '请假申请ID不能为空');
			}

			const res = await db.collection('dh-leave_requests').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '请假申请不存在');
			}
			
			// 附加员工信息
			const enrichedData = await enrichLeaveRequestInfo(res.data[0]);
			return formatResponse(200, enrichedData);
		} catch (error) {
			return formatError(error, '获取请假申请失败');
		}
	},

	/**
	 * 获取请假申请列表（自动关联申请人和审批人信息）
	 */
	async listLeaveRequests(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 默认不显示已删除记录
			query.is_deleted = false;
			
			const res = await db.collection('dh-leave_requests')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();
			
			// 批量附加员工信息
			const enrichedData = await enrichLeaveRequestsList(res.data);
			
			return formatResponse(200, enrichedData, 'success', { count: enrichedData.length });
		} catch (error) {
			return formatError(error, '获取请假申请列表失败');
		}
	},

	/**
	 * 创建请假申请
	 */
	async createLeaveRequest(data) {
		try {
			if (!data.requester_id || !data.leave_type || !data.start_date || !data.end_date) {
				return formatResponse(400, null, '申请人、请假类型、开始日期和结束日期不能为空');
			}

		let leaveData = {
			requester_id: data.requester_id,
				leave_type: parseInt(data.leave_type),
				start_date: data.start_date,
				end_date: data.end_date,
				duration_days: parseInt(data.duration_days) || 0,
				reason: data.reason || '',
				status: parseInt(data.status) || 1,  // 默认待审批
				approved_by: data.approved_by || null,
				approved_time: data.approved_time || null,
				rejection_reason: data.rejection_reason || '',
				is_deleted: false,  // 软删除字段，默认未删除
			create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		leaveData = await autoMountHospitalId(leaveData);

		const res = await db.collection('dh-leave_requests').add(leaveData);
			return formatResponse(201, { _id: res.id }, '请假申请创建成功');
		} catch (error) {
			return formatError(error, '创建请假申请失败');
		}
	},

	/**
	 * 更新请假申请
	 */
	async updateLeaveRequest(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '请假申请ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-leave_requests').doc(id).update(updateData);
			return formatResponse(200, null, '请假申请更新成功');
		} catch (error) {
			return formatError(error, '更新请假申请失败');
		}
	},

	/**
	 * 删除请假申请
	 */
	async deleteLeaveRequest(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '请假申请ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-leave_requests', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '请假申请已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除请假申请失败');
		}
	},

	/**
	 * 批量更新请假申请
	 */
	async batchUpdateLeaveRequests(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-leave_requests').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除请假申请
	 */
	async batchDeleteLeaveRequests(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-leave_requests', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	/**
	 * 批准请假申请
	 */
	async approveLeaveRequest(id, approverId, approverName) {
		try {
			if (!id) {
				return formatResponse(400, null, '请假申请ID不能为空');
			}

			await db.collection('dh-leave_requests').doc(id).update({
				status: 2,  // 2-已批准
				approved_by: approverId,
				approved_time: Date.now(),
				update_time: Date.now()
			});

			return formatResponse(200, null, '请假申请已批准');
		} catch (error) {
			return formatError(error, '批准请假申请失败');
		}
	},

	/**
	 * 拒绝请假申请
	 */
	async rejectLeaveRequest(id, rejectionReason) {
		try {
			if (!id) {
				return formatResponse(400, null, '请假申请ID不能为空');
			}

			await db.collection('dh-leave_requests').doc(id).update({
				status: 3,  // 3-已拒绝
				rejection_reason: rejectionReason || '',
				update_time: Date.now()
			});

			return formatResponse(200, null, '请假申请已拒绝');
		} catch (error) {
			return formatError(error, '拒绝请假申请失败');
		}
	},

	/**
	 * 获取可请假的员工列表（调用公共模块）
	 * @param {String} format - 格式化类型：'default', 'with_role', 'with_mobile', 'full'（默认 'with_role'）
	 * @returns {Object} { code, data, message }
	 */
	async getLeaveEligibleStaff(format = 'with_role') {
		try {
			// 使用公共模块获取可请假的员工列表
			// 包括：医生、护士、护士长、员工、院长、副院长、行政、财务、采购员
			// 排除：患者、纯系统角色（admin、manager）
			const staffList = await getUserList({
				includeRoles: ['doctor', 'nurse', 'head_nurse', 'staff', 'director', 'vice_director', 'administrative', 'finance', 'purchaser'],
				excludeRoles: ['patient'],
				format: format,
				limit: 1000,
				decryptSensitiveInfo: true
			});

			return formatResponse(200, staffList, '查询成功');
		} catch (error) {
			return formatError(error, '获取可请假员工列表失败');
		}
	}
};
